package com.efounder.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.efounder.adapter.MallSelectionPayMultiAdapter;
import com.efounder.bean.MallSelectionPayMultipleBean;
import com.efounder.bean.MallSelectionPayOrderBean;
import com.efounder.bean.UpdateOrderBadgeEvent;
import com.efounder.fragment.selectionpay.SelectionPayPresenter;
import com.efounder.fragment.selectionpay.SelectionPayView;
import com.efounder.mobilemall.R;
import com.efounder.ospopenplanet.wxapi.WXPayEntryActivity;
import com.efounder.util.DialogUtil;
import com.efounder.util.EnvSupportManager;
import com.efounder.util.ToastUtil;
import com.efounder.utils.Utils;
import com.efounder.view.countdownview.CountdownView;
import com.pansoft.mobilemallpay.pays.AliPay;
import com.pansoft.mobilemallpay.pays.OnPayListener;
import com.pansoft.mobilemallpay.pays.PayInter;
import com.pansoft.openplanet.activity.AmountRechargeActivity;
import com.efounder.mvp.base.MvpBaseActivity;
import com.pansoft.openplanet.util.TCMathUtil;
import com.utilcode.util.ConvertUtils;
import com.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

/**
 * @author : zzj
 * e-mail : zhangzhijun@pansoft.com
 * date   : 2018/9/17 20:27
 * desc   : 选择支付 activity
 * version: 1.0
 */
public class SelectionPayActivity extends MvpBaseActivity<SelectionPayPresenter> implements View.OnClickListener, SelectionPayView {


    /**
     * recyclerView
     */
    private RecyclerView rvSelectionPay;
    /**
     * 订单提醒文本
     */
    private TextView tvOrderHint;

    private CountdownView cvSelectionPay;
    /**
     * 支付按钮
     */
    private Button btnPay;

    private LinearLayout llTopOrderHint;
    //币支付方式
    private LinearLayout ll_turbo_pay;
    /**
     * 列表适配器
     */
    private MallSelectionPayMultiAdapter mallSelectionPayMultiAdapter;
    /**
     * 订单id，订单金额，订单title
     */
    private String orderAmount, orderTitle;

    private ArrayList<String> orderIds;
    /**
     * 数据集合
     */
    private List<MallSelectionPayMultipleBean> selectionPayMultipleBeans = new ArrayList<>();
    /**
     * 订单详情的数据类
     */
    private MallSelectionPayOrderBean orderDetail;

    @Override
    protected SelectionPayPresenter initPresenter() {
        return new SelectionPayPresenter(this);
    }

    @Override
    protected int getContentLayoutId() {
        return R.layout.mall_activity_selection_pay;
    }

    public static void start(Context context, ArrayList<String> orderId, String orderAmount, String orderTitle) {
        Intent starter = new Intent(context, SelectionPayActivity.class);
        starter.putStringArrayListExtra("orderId", orderId);
        starter.putExtra("orderAmount", orderAmount);
        starter.putExtra("orderTitle", orderTitle);
        context.startActivity(starter);
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        Bundle bundle = getIntent().getExtras();
        orderIds = bundle.getStringArrayList("orderId");
        orderAmount = bundle.getString("orderAmount");
        orderTitle = bundle.getString("orderTitle");
        findViewById(R.id.title).setVisibility(View.VISIBLE);
        TextView tvTitle = (TextView) findViewById(R.id.tv_title);
        tvTitle.setText(R.string.mall_selection_pay_title);
        ll_turbo_pay = (LinearLayout) findViewById(R.id.ll_turbo_pay);
        tvOrderHint = (TextView) findViewById(R.id.tv_order_hint);
        cvSelectionPay = (CountdownView) findViewById(R.id.cv_selection_pay);
        btnPay = (Button) findViewById(R.id.btn_pay);
        llTopOrderHint = (LinearLayout) findViewById(R.id.ll_top_order_hint);
        llTopOrderHint.setVisibility(View.INVISIBLE);
        tvOrderHint.setVisibility(View.INVISIBLE);
        btnPay.setOnClickListener(this);
        rvSelectionPay = (RecyclerView) findViewById(R.id.mall_rv_selection_pay);
        rvSelectionPay.setLayoutManager(new LinearLayoutManager(this));

        mallSelectionPayMultiAdapter = new MallSelectionPayMultiAdapter(selectionPayMultipleBeans);
        rvSelectionPay.setAdapter(mallSelectionPayMultiAdapter);
        initEvent();
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onResume() {
        super.onResume();
        if (orderIds != null) {
            //请求订单详情
            presenter.getOrderDetailsData("", orderIds.toString());

        }
    }

    @Override
    public void initEvent() {
        //adapter的点击事件
        mallSelectionPayMultiAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                presenter.onAdapterItemClick(adapter, selectionPayMultipleBeans, position);
            }
        });
        //列表中按钮的点击事件
        mallSelectionPayMultiAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                if(view.getId() == R.id.tv_go_recharge){
                    MallSelectionPayMultipleBean.SelectionPay selectionPay = selectionPayMultipleBeans.get(position).getSelectionPay();
                    AmountRechargeActivity.start(SelectionPayActivity.this,selectionPay.getTitle(),selectionPay.getTokenTypeId());
                }
            }
        });

        /**
         * 倒计时结束监听  关闭订单提醒
         */
        cvSelectionPay.setOnCountdownEndListener(new CountdownView.OnCountdownEndListener() {
            @Override
            public void onEnd(CountdownView cv) {
                DialogUtil.showDialogNoCancel(activity, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        finish();
                    }
                },R.string.common_text_hint,activity.getString(R.string.mall_selection_pay_timeout_remind)
                        ,activity.getString(R.string.common_text_confirm));
            }
        });
    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        //支付按钮点击事件
        if (i == R.id.btn_pay) {
            MallSelectionPayMultipleBean selectionPayBean = null;
            //遍历当前选择的支付方式
            for (MallSelectionPayMultipleBean selectionPayMultipleBean : selectionPayMultipleBeans) {
                if (selectionPayMultipleBean.getSelectionPay().isSelectPayWay()) {
                    selectionPayBean = selectionPayMultipleBean;
                }
            }
            //当前是否选择了支付方式
            if (selectionPayBean != null) {
                if (orderDetail != null) {
                    //判断当前支付是现金支付还是积分支付
                    if(selectionPayBean.getItemType() == MallSelectionPayMultipleBean.PAY_WAY_ITEM){
                        //积分支付  积分支付传抵扣积分
                        if(selectionPayBean.getSelectionPay().getSurplusNum().equals("")){
                            ToastUtils.showShort(getString(R.string.mall_selection_pay_get_integral_fail));
                            return;
                        }
                        presenter.pay(activity,selectionPayBean.getPayType(),orderIds.toString(),orderTitle
                                , TCMathUtil.retainAsignDecimalsWithZero(Double.valueOf(selectionPayBean.getSelectionPay().getTokenAmount()),2));
                    }else {
                        //现金去付款  传商品金额
                        presenter.pay(activity,selectionPayBean.getPayType(),orderIds.toString(),orderTitle
                                , TCMathUtil.retainAsignDecimalsWithZero(orderDetail.getPrePayInfo().getOrdersTotalPrice(),2));
                    }

                }else {
                    ToastUtils.showShort(getString(R.string.mall_selection_pay_order_hint));
                }

            } else {
                ToastUtils.showShort(getString(R.string.mall_selection_pay_select_hint));
            }
        }
    }

    private BroadcastReceiver receiver;

    /**
     * 页面监听  不知道做什么的
     */
    @Override
    public void listenerActivityNotifycation() {
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                LocalBroadcastManager.getInstance(SelectionPayActivity.this).unregisterReceiver(this);
                finish();
            }
        }, new IntentFilter(WXPayEntryActivity.FINISH_ORDER_ACTIVITY));
    }


    @Override
    public void getSilverDataSuccess(String silverData) {
        //设置银钻数量
     presenter.loadBalanceData(selectionPayMultipleBeans,orderDetail.getPrePayInfo().getOrdersTotalPrice()
             ,silverData,MallSelectionPayMultipleBean.SILVER_PAY,mallSelectionPayMultiAdapter);
//     mallSelectionPayMultiAdapter.notifyDataSetChanged();
    }

    @Override
    public void getBalanceDataSuccess(String powerData) {
        //设置能量数量
        presenter.loadBalanceData(selectionPayMultipleBeans,orderDetail.getPrePayInfo().getOrdersTotalPrice()
                ,powerData,MallSelectionPayMultipleBean.POWER_PAY,mallSelectionPayMultiAdapter);
//        mallSelectionPayMultiAdapter.notifyDataSetChanged();
    }

    @Override
    public void getFGTBalanceDataSuccess(String fgtBalance) {
        //设置FGT数量
        presenter.loadBalanceData(selectionPayMultipleBeans,orderDetail.getPrePayInfo().getOrdersTotalPrice()
                ,fgtBalance,MallSelectionPayMultipleBean.FGT_PAY,mallSelectionPayMultiAdapter);
//        mallSelectionPayMultiAdapter.notifyDataSetChanged();
    }

    /**
     * 获取订单信息成功
     *
     * @param orderDetail 订单详情数据
     */
    @Override
    public void getDataSuccess(MallSelectionPayOrderBean orderDetail, List<MallSelectionPayMultipleBean> mallSelectionPayMultipleBeans) {
        if (orderDetail != null) {
            this.orderDetail = orderDetail;
            //判断turboChina 支付方式的显示
            if(orderDetail.getPrePayInfo().getTokenUseArray()!=null&&orderDetail.getPrePayInfo().getTokenUseArray().size()>0){
                if(EnvSupportManager.isSupportGooglePlayUpgrade()){
                    ll_turbo_pay.setVisibility(View.VISIBLE);
                }else {
                    ll_turbo_pay.setVisibility(View.GONE);
                }
            }

            selectionPayMultipleBeans.clear();
            selectionPayMultipleBeans.addAll(mallSelectionPayMultipleBeans);
            //获取银钻数量
            presenter.getSilverData();
            //获取能量数量
            presenter.getBanlancefromServer();
            //获取fgt的数量
            presenter.loadFgtBalance();

            orderAmount = TCMathUtil.retainAsignDecimalsWithZero(orderDetail.getPrePayInfo().getOrdersTotalPrice(), 2);
            //设置订单提醒字体颜色高亮
            cvSelectionPay.start(orderDetail.getPrePayInfo().getRemainPayTime());
            String text = String.format(getString(R.string.mall_selection_pay_order_hint3)
                    ," ￥ "+ orderAmount);
            tvOrderHint.setText(Utils.matcherSearchTextSize(getResources().getColor(R.color.op_orange_color)
                    , ConvertUtils.dp2px(16), text, new String[]{orderAmount}));
            llTopOrderHint.setVisibility(View.VISIBLE);
            tvOrderHint.setVisibility(View.VISIBLE);
//            mallSelectionPayMultiAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 支付成功
     *
     * @param finalPay 支付
     */
    @Override
    public void paySuccess(PayInter finalPay) {
        //如果是订单列表了付款，需要通知订单角标刷新
        EventBus.getDefault().post(new UpdateOrderBadgeEvent());
        if (finalPay instanceof AliPay) {
            //阿里支付成功后需要手动跳转到支付成功界面
            //微信会自动跳转到成功界面;
            Intent intent = new Intent(SelectionPayActivity.this, WXPayEntryActivity.class);
            intent.putExtra("type", "ali");
            intent.putExtra("status", "success");
            startActivity(intent);
            finish();
        } else if (finalPay == null) {
            Intent intent = new Intent(SelectionPayActivity.this, WXPayEntryActivity.class);
            intent.putExtra("type", "ali");
            intent.putExtra("status", "success");
            startActivity(intent);
            finish();
        }
    }

    /**
     * 支付失败
     *
     * @param finalPay 支付方式
     * @param msg      失败信息
     * @param code     失败code
     */
    @Override
    public void payFailed(PayInter finalPay, String msg, int code) {
        if (code == OnPayListener.ERROR) {
            ToastUtil.showToast(SelectionPayActivity.this, msg);
            if (finalPay instanceof AliPay) {
                //阿里支付成功后需要手动跳转到支付成功界面
                //微信会自动跳转到成功界面;
                Intent intent = new Intent(SelectionPayActivity.this, WXPayEntryActivity.class);
                intent.putExtra("type", "ali");
                intent.putExtra("status", "failure");
                startActivity(intent);
            } else if (finalPay == null) {
                Intent intent = new Intent(SelectionPayActivity.this, WXPayEntryActivity.class);
                intent.putExtra("type", "ali");
                intent.putExtra("status", "failure");
                startActivity(intent);
            }
        }
    }

    /**
     * 获取fgt积分失败
     */
    @Override
    public void getFGTDataFail() {
        DialogUtil.showDialog(SelectionPayActivity.this, getString(R.string.common_text_hint)
                , getString(R.string.mall_selection_pay_get_integral_fail), getString(R.string.common_text_retry)
                , new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                if (orderIds != null) {
                    //请求订单详情
                    presenter.getOrderDetailsData("", orderIds.toString());

                }
            }
        }, getString(R.string.common_text_cancel), new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                finish();
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (receiver != null) {
            LocalBroadcastManager.getInstance(this).unregisterReceiver(receiver);
        }

    }
}
